<?php
ini_set('display_errors', 1);

class tx_gkeisview_getFlexformFields {
    static function myGetFlexformValue($config, $value) {
        if(! $config['row']['pi_flexform']) {
            // because after creating the plugin it will be empty once
            return NULL;
        }

        $flexformAsArray = t3lib_div::xml2array($config['row']['pi_flexform']);
        $flexformValue   = isset($flexformAsArray['data']['sDEF']['lDEF'][$value]['vDEF']) ? urldecode($flexformAsArray['data']['sDEF']['lDEF'][$value]['vDEF']) : '';

        $flexformValueArray = explode(',', $flexformValue);
        foreach($flexformValueArray as &$flexformValue) {
            $flexformValue = trim($flexformValue);

            // for some reason, $flexformValue is not allways the value only but "value|name"
            if(strpos($flexformValue, '|') != FALSE) {
                $flexformValue = substr($flexformValue, 0, strpos($flexformValue, '|'));
            }
        }

        $flexformValue = implode(',', $flexformValueArray);

        // problem with this
        $flexformValue = preg_match('#Q A#', $flexformValue) ? 'Q+A' : $flexformValue;

        return $flexformValue;
    }

    function __construct() {
        $params = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['gk_eisview']);

        $this->mysqli = new mysqli('localhost', $params["user"], $params["pass"], $params["database"]);
        $this->mysqli->query("SET NAMES 'utf8'");

        $this->SHOW_ONLY_POSSIBLE_FLEXFORM_VALUES = $params['show_only_possible_flexform_values'];

        /*
         * Use this instead of $connect_error if you need to ensure
         * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
         */
        if(mysqli_connect_error()) {
            die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
        }
    }

    function getYears($config) {
        $optionList = array();

        array_push($optionList, array("Alle", ""));

        $results = $this->mysqli->query("select distinct event_year from view_event where event_year !=0 order by event_year desc");

        $result_array = array();
        while($result = $results->fetch_assoc()) {
            array_push($result_array, $result);
        }
        $results->close();

        foreach($result_array as $event_year) {
            array_push($optionList, array($event_year["event_year"], $event_year["event_year"]));
        }

        $config['items'] = array_merge($config['items'], $optionList);

        return $config;
    }

    function getEventDates($config) {
        $optionList = array();
        array_push($optionList, array("Alle", "all"));
        array_push($optionList, array("Alle Heuer", "all_this_year"));

        if($this->SHOW_ONLY_POSSIBLE_FLEXFORM_VALUES) {
            $catType  = self::myGetFlexformValue($config, 'category') == 'all' ? '' : self::myGetFlexformValue($config, 'category');
            $catType2 = self::myGetFlexformValue($config, 'subcategory') == 'all' ? '' : self::myGetFlexformValue($config, 'subcategory');

            if($catType2) {
                $catType2Exploded   = explode(',', $catType2);
                $catType2QueryArray = array();

                foreach($catType2Exploded as $catType2Value) {
                    $catType2QueryArray[] = "cat_type2 LIKE '%$catType2Value%'";
                }

                $catType2Query = implode(' OR ', $catType2QueryArray);
            }
            $catType2Query = $catType2 ? "and $catType2Query" : '';

            $results = $this->mysqli->query("select distinct date_name from view_event where cat_type LIKE '%$catType%' $catType2Query order by date_name asc");
        } else {
            $results = $this->mysqli->query("select distinct date_name from view_event order by date_name asc");
        }

        $result_array = array();
        while($result = $results->fetch_assoc()) {
            array_push($result_array, $result);
        }
        $results->close();

        foreach($result_array as $event_date) {
            array_push($optionList, array($event_date["date_name"], $event_date["date_name"]));
        }

        $config['items'] = array_merge($config['items'], $optionList);

        return $config;
    }

    function getDailyFeaturedDates($config) {
        $optionList = array();
        array_push($optionList, array("Kein", ""));

        $results = $this->mysqli->query("select distinct date_name from view_event_appearance order by date_name asc");

        $result_array = array();
        while($result = $results->fetch_assoc()) {
            array_push($result_array, $result);
        }
        $results->close();

        foreach($result_array as $event_date) {
            array_push($optionList, array($event_date["date_name"], $event_date["date_name"]));
        }

        $config['items'] = array_merge($config['items'], $optionList);

        return $config;
    }

    function formatDate($date_string, $getOnlyYear = FALSE) {
        $temp_date_string = explode(" ", $date_string);
        $date_array       = explode("-", $temp_date_string[0]);

        $dateFormat = $getOnlyYear ? 'Y' : 'd.m.Y';

        return date($dateFormat, mktime(0, 0, 0, $date_array[1], $date_array[2], $date_array[0]));
    }

    function getEventLocations($config) {
        $optionList = array();
        array_push($optionList, array("Alle", "all"));

        if($this->SHOW_ONLY_POSSIBLE_FLEXFORM_VALUES) {
            $eventDays = self::myGetFlexformValue($config, 'eventday') == 'all' ? '' : self::myGetFlexformValue($config, 'eventday');
            $eventDays = $eventDays == 'all_this_year' ? date("Y") : $eventDays;

            if($eventDays) {
                $eventDaysArray         = explode(',', $eventDays);
                $eventYearQueryINString = '';
                foreach($eventDaysArray as $eventDay) {
                    $eventDayDotExploded = explode('.', $eventDay);
                    $eventYear           = isset($eventDayDotExploded[2]) ? $eventDayDotExploded[2] : $eventDays;

                    $eventYearQueryINString .= $eventYear ? "'$eventYear'," : '';
                }
                $eventYearQueryINString = substr($eventYearQueryINString, 0, - 1);
            } else {
                $eventYearQueryINString = '';
            }

            $eventYearQuery = $eventYearQueryINString ? "WHERE event_year IN($eventYearQueryINString)" : '';

            $results = $this->mysqli->query("select distinct(location_name) from view_location $eventYearQuery order by event_year desc, location_name asc");
        } else {
            $results = $this->mysqli->query("select distinct(location_name) from view_location order by event_year desc, location_name asc");
        }

        $result_array = array();
        while($result = $results->fetch_assoc()) {
            array_push($result_array, $result);
        }
        $results->close();

        foreach($result_array as $event_location) {
            array_push($optionList, array($event_location["location_name"], $event_location["location_name"]));
        }

        $config['items'] = array_merge($config['items'], $optionList);

        return $config;
    }

    function getEventNames($config) {
        $optionList = array();
        array_push($optionList, array("Alle", "all"));

        if($this->SHOW_ONLY_POSSIBLE_FLEXFORM_VALUES) {
            // cat types 
            $catType  = self::myGetFlexformValue($config, 'category') == 'all' ? '' : self::myGetFlexformValue($config, 'category');
            $catType2 = self::myGetFlexformValue($config, 'subcategory') == 'all' ? '' : self::myGetFlexformValue($config, 'subcategory');

            if($catType2) {
                $catType2Exploded   = explode(',', $catType2);
                $catType2QueryArray = array();

                foreach($catType2Exploded as $catType2Value) {
                    $catType2QueryArray[] = "cat_type2 LIKE '%$catType2Value%'";
                }

                $catType2Query = implode(' OR ', $catType2QueryArray);
            }
            $catType2Query = $catType2 ? "and ($catType2Query)" : '';

            // event days
            $eventDays = self::myGetFlexformValue($config, 'eventday') == 'all' ? '' : self::myGetFlexformValue($config, 'eventday');
            $eventDays = $eventDays == 'all_this_year' ? date("Y") : $eventDays;

            if($eventDays) {
                $eventDaysArray         = explode(',', $eventDays);
                $eventYearQueryINString = '';
                foreach($eventDaysArray as $eventDay) {
                    $eventDayDotExploded = explode('.', $eventDay);
                    $eventYear           = isset($eventDayDotExploded[2]) ? $eventDayDotExploded[2] : $eventDays;

                    $eventYearQueryINString .= $eventYear ? "'$eventYear'," : '';
                }
                $eventYearQueryINString = substr($eventYearQueryINString, 0, - 1);
            } else {
                $eventYearQueryINString = '';
            }

            $eventYearQuery = $eventYearQueryINString ? "and event_year IN($eventYearQueryINString)" : '';

            // location names
            $eventLocation = self::myGetFlexformValue($config, 'eventlocation') == 'all' ? '' : self::myGetFlexformValue($config, 'eventlocation');

            $eventLocationQuery = $eventLocation ? "and location_name IN('".preg_replace('#,#', "','", $eventLocation)."')" : '';

            $results = $this->mysqli->query("select title, location_name, event_year, event_id from view_event where cat_type LIKE '%$catType%' $catType2Query $eventYearQuery $eventLocationQuery order by event_year desc, title asc");
        } else {
            $results = $this->mysqli->query("select title, location_name, event_year, event_id from view_event order by event_year desc, title asc");
        }

        $result_array = array();
        while($result = $results->fetch_assoc()) {
            array_push($result_array, $result);
        }
        $results->close();

        foreach($result_array as $event_name) {
            array_push($optionList, array($event_name["title"]." (".$event_name["location_name"].", ".$event_name["event_year"].")", $event_name["event_id"]));
        }

        $config['items'] = array_merge($config['items'], $optionList);

        return $config;
    }

    function getSubCategories($config) {
        $optionList = array();
        array_push($optionList, array("Unterkategorien", "all"));

        $config['items'] = array_merge($config['items'], $optionList);

        return $config;
    }

    function __destruct() {
        $this->mysqli->close();
    }
}

?>